# $Id$

module ApplicationHelper

  def calendar_is_holiday?(cur_date)
    return false unless cur_date
    return false unless cur_date.is_a?(Date)
    return [0,6].include?(cur_date.wday)
  end

  def calendar_work_days(start_date, end_date)
    return 0 unless (start_date && end_date)
    begin
      start_date = Date.parse(start_date) unless start_date.is_a?(Date)
      end_date = Date.parse(end_date) unless end_date.is_a?(Date)
    rescue
      return 0
    end

    ret_val = 0
    start_date.step(end_date, 1){|cur_date| ret_val+=1 unless calendar_is_holiday?(cur_date)}

    return ret_val
  end

  def issue_spent_hours(issue, start_date, end_date)
    return 0 unless (start_date && end_date)
    begin
      start_date = Date.parse(start_date) if start_date.is_a?(String)
      end_date = Date.parse(end_date) if start_date.is_a?(String)
    rescue
      return 0
    end
    return TimeEntry.sum(:hours, :conditions => ["issue_id = ? and spent_on >= ? and spent_on <= ?", issue.id, start_date, end_date])
  end

  def issue_first_esitimate(issue)
    journal = Journal.find(:first,
                :conditions => ["#{Journal.table_name}.journalized_id = ? and #{JournalDetail.table_name}.prop_key = 'estimated_hours'", issue.id],
                :include => :details,
                :order => "#{Journal.table_name}.id asc" )
    return "" unless journal
    detail = journal.details.detect(nil){|detail| detail.prop_key == 'estimated_hours'}
    return "" unless detail
    return detail.value
  end

end
